package com.quanshu.exchange.ui.gui.message.mass_send;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.quanshu.exchange.R;
import com.quanshu.exchange.support.db.UserDao;
import com.quanshu.exchange.support.entity.UserEntity;
import com.quanshu.exchange.support.entity.tmp.TmpLabelEntity;
import com.quanshu.exchange.support.utils.AppUtils;
import com.quanshu.exchange.support.utils.CheckUtil;
import com.quanshu.exchange.support.utils.RxViewHelper;
import com.quanshu.exchange.ui.base.BaseActivity;
import com.quanshu.exchange.ui.base.recycler.BaseViewHolder;
import com.quanshu.exchange.ui.base.recycler.DataDisplayer;
import com.quanshu.exchange.ui.base.recycler.LayoutWrapper;
import com.quanshu.exchange.ui.base.recycler.SingleAdapter;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

public class LabelDetailActivity extends BaseActivity {

    @BindView(R.id.back)
    LinearLayout back;
    @BindView(R.id.label_title)
    TextView labelTitle;
    @BindView(R.id.ok_btn)
    ImageView okBtn;
    @BindView(R.id.recycler_view)
    RecyclerView recyclerView;
    private SingleAdapter<UserEntity> adapter;
    private List<UserEntity> labelMember = new ArrayList<>();
    private TmpLabelEntity labelEntity;
    private List<String> selectedUser;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_label_detail);
        ButterKnife.bind(this);
        initIntent();
        initView();
        initData();
        initListener();
    }

    private void initIntent() {
        labelEntity = (TmpLabelEntity) getIntent().getSerializableExtra("TmpLabelEntity");
        selectedUser = (List<String>) getIntent().getSerializableExtra("List<String>");
    }

    private void initView() {
        labelTitle.setText(labelEntity.getLabelName());
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        adapter = new SingleAdapter<>(new DataDisplayer<UserEntity>(this, R.layout.item_select_friend_layout) {
            @Override
            public void bindData(BaseViewHolder holder, LayoutWrapper<UserEntity> wrapper, UserEntity item, int position) {
                holder.setRoundImageUrl(R.id.friend_avatar, item.getAvatar(), R.drawable.default_avatar);
                holder.setText(R.id.friend_name, AppUtils.getUserName(item));
                String letter = AppUtils.getUserInitialLetter(item);
                // 处理分割线
                int nextPosition = position + 1;
                if (nextPosition < labelMember.size()) {
                    UserEntity nextUser = labelMember.get(position + 1);
                    String nextHead = AppUtils.getInitialLetter(AppUtils.getUserName(nextUser));
                    if (letter.equals(nextHead)) {
                        holder.setVisibility(R.id.item_contacts_bottom_divider, View.VISIBLE);
                    } else {
                        holder.setVisibility(R.id.item_contacts_bottom_divider, View.GONE);
                    }
                }
                if (position == labelMember.size() - 1) {
                    holder.setVisibility(R.id.item_contacts_last_bottom_divider, View.VISIBLE);
                } else {
                    holder.setVisibility(R.id.item_contacts_last_bottom_divider, View.GONE);
                }
                // 处理head字母
                if (position == 0) {
                    holder.setVisibility(R.id.friend_sort_letter, View.VISIBLE);
                    holder.setText(R.id.friend_sort_letter, letter);
                } else {
                    int lastPosition = position - 1;
                    if (lastPosition < 0) {
                        lastPosition = 0;
                    }
                    UserEntity lastUser = labelMember.get(lastPosition);
                    if (letter.equals(AppUtils.getUserInitialLetter(lastUser))) {
                        holder.setVisibility(R.id.friend_sort_letter, View.GONE);
                    } else {
                        holder.setVisibility(R.id.friend_sort_letter, View.VISIBLE);
                        holder.setText(R.id.friend_sort_letter, letter);
                    }
                }
                ImageView checkBox = holder.getView(R.id.friend_check);
                if (CheckUtil.isValidate(selectedUser)) {
                    if (selectedUser.contains(item.getMemberid())) {
                        checkBox.setSelected(true);
                    } else {
                        checkBox.setSelected(false);
                    }
                } else {
                    checkBox.setSelected(false);
                }
                checkBox.setOnClickListener(view -> {
                    boolean status = checkBox.isSelected();
                    if (selectedUser == null) {
                        selectedUser = new ArrayList<>();
                    }
                    if (!status) {
                        selectedUser.add(item.getMemberid());
                    } else {
                        Iterator<String> it = selectedUser.iterator();
                        while (it.hasNext()) {
                            if (it.next().contains(item.getMemberid())) {
                                it.remove();
                                break;
                            }
                        }
                    }
                    checkBox.setSelected(!status);
                    adapter.notifyDataSetChanged();
                });
            }
        });
        recyclerView.setAdapter(adapter);
    }

    private void initData() {
        String str = labelEntity.getLabelMemberId();
        List<UserEntity> userEntityList = UserDao.getInstance().queryForAll();
        if (str != null && str.length() > 0 && userEntityList != null && userEntityList.size() > 0) {
            String[] split = str.split(",");
            for (String s : split) {
                for (UserEntity u : userEntityList) {
                    if (s.equals(u.getMemberid())) {
                        labelMember.add(u);
                    }
                }
            }
        }
        if (labelMember != null && labelMember.size() > 0) {
            AppUtils.sortDataByPinYin(labelMember);
            adapter.setData(labelMember);
        }
    }

    private void initListener() {

        RxViewHelper.getInstance().clicks(back, aVoid -> finish());
        RxViewHelper.getInstance().clicks(okBtn, aVoid -> doClickOk());
    }

    private void doClickOk() {
        Intent intent = getIntent();
        intent.putExtra("List<String>", (Serializable) selectedUser);
        intent.putExtra("String", labelEntity.getLabelId());
        setResult(RESULT_OK, intent);
        finish();
    }
}
